package com.showdor.dataSync;

import com.showdor.entity.Message;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Qualifier;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.jdbc.core.BeanPropertyRowMapper;
import org.springframework.jdbc.core.JdbcTemplate;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Service;

import javax.annotation.PostConstruct;
import javax.annotation.Resource;
import java.io.*;
import java.text.SimpleDateFormat;
import java.util.Date;
import java.util.List;

/**
 * @author showdor
 * @email chuanqi@outlook.com
 * @date 2025/2/21
 */
//@Service
@Slf4j
public class Data185to186SyncService extends DataSyncService {
    /**
     * 存储上次同步时间的文件
     */
    static final String LAST_SYNC_TIME_FILE = "lastSyncTime185_186.txt";
    private static final SimpleDateFormat FORMATTER = new SimpleDateFormat("yyyy-MM-dd HH:mm:ss");
    @Resource
    @Qualifier("x185sourceJdbcTemplate")
    private JdbcTemplate x185sourceJdbcTemplate;

    @Resource
    @Qualifier("y186targetJdbcTemplate")
    private JdbcTemplate y186targetJdbcTemplate;


    @PostConstruct
    public void init() {
        // 初始化时检查文件是否存在，若不存在则创建并写入默认时间
        initSyncTime(LAST_SYNC_TIME_FILE);
    }

    @Scheduled(fixedDelayString = "${sync.interval}")
    public void syncData() {
        long now = System.currentTimeMillis();
        log.info("开始同步从185-fromx.message to 186-toy.cnyw, 同步时间: {}", FORMATTER.format(now));
        int size = syncData(x185sourceJdbcTemplate, y186targetJdbcTemplate, LAST_SYNC_TIME_FILE);
        if (size > 0) {
            log.info("从185-fromx.message to 186-toy.cnyw同步完成，共同步{}条数据 耗时{}ms ", size, System.currentTimeMillis() - now);
        } else {
            log.info("从185-fromx.message to 186-toy.cnyw同步完成，无新增数据 耗时{}ms", System.currentTimeMillis() - now);
        }
    }


}
